#include "ifmform.h"
#include "ui_ifmform.h"
#include "db.h"
#include <QDebug>
#include <QNetworkAccessManager>
#include <QFile>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QSize>
#include <QMessageBox>
#include "flatui.h"

IfmForm::IfmForm(const QString &pname,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::IfmForm)
{
    ui->setupUi(this);
    FlatUI::setPushButtonQss(ui->pushButton);
    this->initForm(pname);
}
IfmForm::IfmForm(QWidget *parent):
    QWidget(parent),
    ui(new Ui::IfmForm)
{
    ui->setupUi(this);
    FlatUI::setPushButtonQss(ui->pushButton);
}

IfmForm::~IfmForm()
{
    delete ui;
}

void IfmForm::initForm(const QString &pname)
{
    //设置窗体模式
    this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint);
    //读取数据
    QSqlQuery dataSet = Db::getProductIfm(pname);
    dataSet.next();
    QNetworkAccessManager * manager = new QNetworkAccessManager();
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ReplyPixmapLoad(QNetworkReply*)));
    manager->get(QNetworkRequest(QUrl(dataSet.value("picture_address").toString())));    // 这里的url一定要带上http://头的， 跟在浏览器里输入其它链接不太一样，浏览器里面会自动转的，这里需要手动加上。
    ui->label_id->setText(dataSet.value("pid").toString());
    ui->label_cno->setText(dataSet.value("cname").toString());
    ui->label_pdesc->setText(dataSet.value("pdesc").toString());
    ui->label_pname->setText(dataSet.value("pname").toString());
    ui->label_position->setText(dataSet.value("position").toString());
    ui->label_price->setText(dataSet.value("price").toString());
    //this->setAttribute(Qt::WA_TranslucentBackground);
}

void IfmForm::ReplyPixmapLoad(QNetworkReply* reply)
{
    if(reply->error() == QNetworkReply::NoError)
      {
            QByteArray bytes = reply->readAll();
            QPixmap pixmap;
            pixmap.loadFromData(bytes);
            QSize picSize(200,140);
            pixmap = pixmap.scaled(picSize, Qt::KeepAspectRatio);
            ui->label_picture->setPixmap(pixmap);
//            QFile file("test.png");
//            if (file.open(QIODevice::Append))
//            {
//              file.write(bytes);
//            }
//            file.close();
      }
      else
      {
            QString dlgTitle="error";
            QString strInfo="fail to load image";
            QMessageBox::information(this, dlgTitle, strInfo,QMessageBox::Ok,QMessageBox::NoButton);
      }
}



void IfmForm::on_pushButton_clicked()
{
    this->close();
}
